﻿using System;
using System.Threading;
using System.Windows.Forms;
using System.Globalization;
using ALDIOrganizer.Properties;

namespace ALDIOrganizer
{
    public partial class Program
    {
        /// <summary>
        /// Shows a message box informing the user about an unhandled exception. Does not terminate the application
        /// </summary>
        /// <param name="pException">
        /// The exception thrown
        /// </param>
        /// <remarks>
        /// Used by CurrentDomain UnhandledException and Application.ThreadException event handlers.
        /// 
        /// In principle, it should never actually be called:
        /// it only catches and responds to exceptions that were not handled
        /// otherwise throughout the application; in other words, if there are
        /// some unidentified bugs left. 
        /// </remarks>
        static void ReactTo(Exception pException)
        {
            var message = String.Concat(
                    "Ay ay ay! ALDI Organizer has just crashed! My apologies. ",
                    Environment.NewLine,
                    "The error was: ",
                    pException.Message.ToLower(),
                    Environment.NewLine,
                    "Do you want to try and ignore it? The program will not be terminated if so, but it may be unstable. ",
                    Environment.NewLine,
                    "If you click No, you'll close the application.");

            var couldLogIt = true;
            try
            {
                LogError("Crash", pException);
                _log.Close();
            }
            catch
            {
                couldLogIt = false;
            }
            finally
            {
                message += String.Concat(
                    Environment.NewLine,
                    couldLogIt ? "The error has been logged." : "I could not log this error.");

            }
            if (MessageBox.Show(
                message,
                Resources.MESSAGEBOX_ERROR_CRASH_Caption,
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Error) == DialogResult.Yes)
            {
                return;
            }
            Quit();
        }
    }
}
